/**
 * 2017，thor.com，all rights reserved。
 * 
 * Project：		palmmall-core
 * Filename：	PassengerFlowDaoImpl.java
 * Created：		2017年4月27日
 * Creator：		wolv
 */
package com.thor.palmmall.dao.rpt.passengerflow;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.thor.commons.exception.ThorServiceException;
import com.thor.commons.util.Assert;
import com.thor.dao.BasicDao;
import com.thor.palmmall.api.rpt.Report;
import com.thor.palmmall.api.rpt.passengerflow.DailyPassengerFlowReportParam;

/**
 * @author wolv
 *
 */
@Transactional(rollbackFor = Exception.class, propagation = Propagation.NOT_SUPPORTED)
public class PassengerFlowRptDaoImpl extends BasicDao implements PassengerFlowRptDao {

  @SuppressWarnings("unchecked")
  public Report calcDailyReport(DailyPassengerFlowReportParam param) throws ThorServiceException {
    Assert.assertArgumentNotNull(param, "param");

    param.validate();

    Query query = DailyPassengerFlowReportHqlBuilder.getInstance().build(param);
    List<Object[]> rawReports = query.getResultList();

    return Report.readFrom(rawReports);
  }

  @Override
  public void removePassengerFlowByDay(Date date) {

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    Date fromTime = calendar.getTime();

    calendar.set(Calendar.HOUR, calendar.getActualMaximum(Calendar.HOUR));
    calendar.set(Calendar.MINUTE, calendar.getActualMaximum(Calendar.MINUTE));
    calendar.set(Calendar.SECOND, calendar.getActualMaximum(Calendar.SECOND));

    Date toTime = calendar.getTime();

    String hql = "delete from " + PDailyPassengerFlow.class.getName()
        + " where date >=:fromTime and toTime<:toTime";
    Query query = em.createQuery(hql);
//    query.setParameter("fromTime", fromTime);
//    query.set
//    query.setParameter("toTime", toTime);
    query.executeUpdate();

  }

  @PersistenceContext(unitName = "${thor-webui-core.persistent-unit}")
  protected EntityManager em;
}
